// custom-tab-bar/index.js
Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#ff4757",
    list: [
      {
        pagePath: "/pages/index/index",
        iconPath: "/icons/home-outline.svg",
        selectedIconPath: "/icons/home-filled.svg",
        text: "首页",
      },
      {
        pagePath: "/pages/category/category",
        iconPath: "/icons/category-outline.svg",
        selectedIconPath: "/icons/category-filled.svg",
        text: "分类",
      },
      {
        pagePath: "/pages/cart/cart",
        iconPath: "/icons/cart-outline.svg",
        selectedIconPath: "/icons/cart-filled.svg",
        text: "购物车",
        // 购物车特殊配置
        isCart: true,
        showBackButton: false,
        backButtonIcon: "‹",
      },
      {
        pagePath: "/pages/profile/profile",
        iconPath: "/icons/profile-outline.svg",
        selectedIconPath: "/icons/profile-filled.svg",
        text: "个人中心",
      },
    ],
  },

  attached() {
    console.log("TabBar attached() called");
    // 根据当前页面路径设置选中状态
    this.updateSelectedFromCurrentPage();

    // 获取购物车数量
    this.getCartCount();
  },

  // 页面显示时更新选中状态和购物车数量
  show() {
    console.log("TabBar show() called");
    // 根据当前页面路径设置选中状态
    this.updateSelectedFromCurrentPage();

    // 获取购物车数量
    this.getCartCount();
  },

  methods: {
    // 根据当前页面路径更新选中状态
    updateSelectedFromCurrentPage() {
      const pages = getCurrentPages();
      if (pages.length === 0) return;

      const currentPage = pages[pages.length - 1];
      const currentPath = `/${currentPage.route}`;

      console.log("TabBar updateSelectedFromCurrentPage:", currentPath);

      // 设置当前选中的tab
      const selectedIndex = this.data.list.findIndex(
        (item) => item.pagePath === currentPath
      );

      console.log("TabBar selectedIndex:", selectedIndex);

      if (selectedIndex !== -1) {
        this.setData({
          selected: selectedIndex,
        });
      }
    },
    // 获取购物车数量
    getCartCount() {
      const app = getApp();
      const cartCount = app.globalData.cartCount || 0;
      this.setData({ cartCount });
    },

    // Tab点击事件
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;

      console.log("TabBar switchTab:", url, index);

      // 更新选中状态
      this.setData({
        selected: index,
      });

      // 执行页面跳转
      wx.switchTab({
        url: url,
      });
    },
  },
});
